from django.shortcuts import render, redirect, reverse
from django.utils.deprecation import MiddlewareMixin
from web import models
from django.conf import settings
from django.urls import reverse
import datetime


# 面向对象封装
class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


"""可看看中间键流程 平板有图  看视频100"""


class AuthMiddlewares(MiddlewareMixin):

    def process_request(self, request):
        """如果用户已登录，则request赋值"""
        request.tracer = Tracer()
        user_id = request.session.get('user_id', 0)
        user_object = models.User.objects.filter(id=user_id).first()
        request.tracer.user = user_object

        # print(user_object)
        # print(request.path_info)
        # 白名单：用户不登录都可以访问
        """1, 获取当前用户的url"""
        """2, 检查url是否在白名单中，如果在可以继续访问，如果不在则进行判断是否的登录"""
        if request.path_info in settings.WHITE_REGEX_URL_LIST:  # request.path_info 当前的url
            return  # 返回空，表示通过
        # if not request.path_info in settings.WHITE_REGEX_URL_LIST:  # request.path_info 当前的url
        #     if not request.tracer:
        #         return redirect(reverse('web_login'))

        # if not request.tracer:
        #     redirect('web_login')
        # if not request.tracer:

        # 登陆成功之后，我们访问后台管理是，获取用户的所有额度
        # 方式一：免费额度在交易记录中存储
        if request.tracer.user:
            # 获取当前用户id值最大，也就是最新的交易记录
            _object = models.Transaction.objects.filter(user=user_object).order_by('-id').first()
            # 判断它现在是否已过期
            current_datetime = datetime.datetime.now()
            if _object.end_datetime and _object.end_datetime < current_datetime:
                # 过期
                _object = models.Transaction.objects.filter(user=user_object, status=2,
                                                            price_policy__category=1).first()

            request.tracer.price_policy = _object.price_policy

        # 方式二；免费的额度存储配置文件

    def process_view(self, request, view, args, kwargs):
        # 判断URL是否是以manage开头
        # 如果是
        # 判断是我创建 or 我参与的
        if not request.path_info.startswith('/web/manage/'):
            return

        project_id = kwargs.get('project_id')

        # 是否我创建的
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_object:
            # 如果创建的项目，我就让他通过
            request.tracer.project = project_object
            return

        # 是否我参与的项目
        project_user_project = models.ProjectUser.objects.filter(user=request.tracer.user,
                                                                 project_id=project_id).first()
        if project_user_project:
            # 是我参与的项目
            request.tracer.project = project_user_project.project
            return
        return redirect('web_project_list')
